<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class Base extends Model
{
    protected $table = '';
    public $timestamps = false;

    public function __construct($table, array $attributes = [])
    {
        $this->table = $table;
        parent::__construct($attributes);
    }

    public function getSingle($condition, $fields)
    {
        $document = DB::table($this->table)->where($condition)->get($fields)->toArray();
        return self::objToArray($document);
    }

    public function insertSingle($data)
    {
        $result = DB::table($this->table)->insertGetId($data);
        return $result;
    }

    public function insertBatch($data)
    {
        $result = DB::table($this->table)->insert($data);
        return $result;
    }

    public function singleUpdate($condition, $data)
    {
        return DB::table($this->table)->where($condition)->update($data);
    }

    //返回数组
    public function objToArray($document)
    {
        return json_decode(json_encode($document), true);
    }


    /*
     * redis 键加入缓存过期时间
     * @param [$key] 需要过期时间的redis key
     * @param [$day]  过期天数 30天
     *
     * */
    public function ttlRedisKey($key, $time = 2592000)
    {
        do {
            //获取key 过期时间
            $ttl = Redis::TTL($key);
            if ($ttl == -1) {
                Redis::EXPIRE($key, $time);
            }
        } while (false);
    }
}
